use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        // Create raft_logs table
        manager
            .create_table(
                Table::create()
                    .table(RaftLogs::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(RaftLogs::LogIndex)
                            .big_integer()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(RaftLogs::LogTerm).big_integer().not_null())
                    .col(ColumnDef::new(RaftLogs::EntryType).string().not_null())
                    .col(ColumnDef::new(RaftLogs::EntryData).binary())
                    .col(
                        ColumnDef::new(RaftLogs::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .to_owned(),
            )
            .await?;

        // Create raft_meta table
        manager
            .create_table(
                Table::create()
                    .table(RaftMeta::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(RaftMeta::KeyName)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(RaftMeta::LogIndex).big_integer())
                    .col(ColumnDef::new(RaftMeta::LogTerm).big_integer())
                    .col(ColumnDef::new(RaftMeta::VoteFor).big_integer())
                    .col(ColumnDef::new(RaftMeta::Committed).big_integer())
                    .col(
                        ColumnDef::new(RaftMeta::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .to_owned(),
            )
            .await?;

        // Create cluster_state table
        manager
            .create_table(
                Table::create()
                    .table(ClusterState::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ClusterState::Id)
                            .integer()
                            .not_null()
                            .primary_key()
                            .auto_increment(),
                    )
                    .col(ColumnDef::new(ClusterState::StateData).binary().not_null())
                    .col(ColumnDef::new(ClusterState::LastApplied).big_integer())
                    .col(
                        ColumnDef::new(ClusterState::Version)
                            .big_integer()
                            .not_null()
                            .default(1),
                    )
                    .col(
                        ColumnDef::new(ClusterState::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .to_owned(),
            )
            .await?;

        // Create nodes table
        manager
            .create_table(
                Table::create()
                    .table(Nodes::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Nodes::NodeId)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Nodes::Address).string().not_null())
                    .col(ColumnDef::new(Nodes::Status).string().not_null())
                    .col(ColumnDef::new(Nodes::Metadata).json().not_null())
                    .col(
                        ColumnDef::new(Nodes::LastSeen)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(Nodes::JoinedAt)
                            .timestamp_with_time_zone()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(Nodes::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .to_owned(),
            )
            .await?;

        // Create configurations table
        manager
            .create_table(
                Table::create()
                    .table(Configurations::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Configurations::KeyName)
                            .string()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Configurations::Value).json().not_null())
                    .col(ColumnDef::new(Configurations::Description).string())
                    .col(
                        ColumnDef::new(Configurations::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(Configurations::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .to_owned(),
            )
            .await?;

        // Create indexes
        manager
            .create_index(
                Index::create()
                    .if_not_exists()
                    .name("idx_raft_logs_term_index")
                    .table(RaftLogs::Table)
                    .col(RaftLogs::LogTerm)
                    .col(RaftLogs::LogIndex)
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .if_not_exists()
                    .name("idx_nodes_status")
                    .table(Nodes::Table)
                    .col(Nodes::Status)
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(RaftLogs::Table).to_owned())
            .await?;
        manager
            .drop_table(Table::drop().table(RaftMeta::Table).to_owned())
            .await?;
        manager
            .drop_table(Table::drop().table(ClusterState::Table).to_owned())
            .await?;
        manager
            .drop_table(Table::drop().table(Nodes::Table).to_owned())
            .await?;
        manager
            .drop_table(Table::drop().table(Configurations::Table).to_owned())
            .await?;

        Ok(())
    }
}

#[derive(Iden)]
enum RaftLogs {
    Table,
    LogIndex,
    LogTerm,
    EntryType,
    EntryData,
    CreatedAt,
}

#[derive(Iden)]
enum RaftMeta {
    Table,
    KeyName,
    LogIndex,
    LogTerm,
    VoteFor,
    Committed,
    UpdatedAt,
}

#[derive(Iden)]
enum ClusterState {
    Table,
    Id,
    StateData,
    LastApplied,
    Version,
    UpdatedAt,
}

#[derive(Iden)]
enum Nodes {
    Table,
    NodeId,
    Address,
    Status,
    Metadata,
    LastSeen,
    JoinedAt,
    UpdatedAt,
}

#[derive(Iden)]
enum Configurations {
    Table,
    KeyName,
    Value,
    Description,
    CreatedAt,
    UpdatedAt,
}
